<?php


namespace app\common\listener;

use app\admin\model\Config as ConfigModel;
use app\admin\model\Module as ModuleModel;
use think\facade\Env;
use think\Request;
use Closure;
/**
 * 初始化配置信息行为
 * 将系统配置信息合并到本地配置
 * @package app\common\behavior
 * @author CaiWeiMing <314013107@qq.com>
 */
class Config
{
    /**
     * 执行行为 run方法是Behavior唯一的接口
     * @access public
     * @return void
     */
    public function handle(Request $request, Closure $next)
    {
        // 读取系统配置
        $system_config = cache('system_config');

        if (!$system_config) {
            $ConfigModel = new ConfigModel();
            $system_config = $ConfigModel->getConfig();

            // 所有模型配置
            $module_config = ModuleModel::where('config', '<>', '')->column('config', 'name');

            foreach ($module_config as $module_name => $config) {
                $system_config[strtolower($module_name) . '_config'] = json_decode($config, true);
            }
            // 非开发模式，缓存系统配置
            if ($system_config['develop_mode'] == 0) {
                cache('system_config', $system_config);
            }
        }


        // 设置配置信息

        \think\facade\Config::set($system_config, 'app');
    }

    /**
     * 获取当前运行入口名称
     * @access protected
     * @codeCoverageIgnore
     * @return string
     */
    protected function getScriptName(): string
    {
        if (isset($_SERVER['SCRIPT_FILENAME'])) {
            $file = $_SERVER['SCRIPT_FILENAME'];
        } elseif (isset($_SERVER['argv'][0])) {
            $file = realpath($_SERVER['argv'][0]);
        }

        return isset($file) ? pathinfo($file, PATHINFO_FILENAME) : '';
    }
}
